<template>
  <el-form class="login-form Login_input" status-icon :rules="loginRules" ref="loginForm" :model="loginForm"
           label-width="0">
    <el-form-item prop="username" style="margin-bottom: 20px">
      <el-input size="small" @keyup.enter.native="handleLogin" v-model="loginForm.username" auto-complete="off"
                placeholder="请输入用户名">
        <i slot="prefix" class="fa fa-user-o"></i>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input size="small" @keyup.enter.native="handleLogin" :type="passwordType" v-model="loginForm.password"
                :value="loginForm.password" auto-complete="off" placeholder="请输入密码">
        <i class="el-icon-view el-input__icon" slot="suffix" @click="showPassword"></i>
        <i slot="prefix" class="fa fa-key" aria-hidden="true"></i>
      </el-input>
    </el-form-item>
    <el-checkbox v-model="checked" style="margin-top: 5px">记住账号</el-checkbox>
    <el-form-item>
      <el-button type="primary" size="small" @click.native.prevent="handleLogin" class="login-submit">登 录</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  import {isvalidUsername} from "@/utils/validate";
  import {setToken} from "@/utils/auth"; // 验权

  import {Loading} from "element-ui";

  export default {
    name: "userlogin",
    data() {
      const validateUsername = (rule, value, callback) => {
        if (!value) {
          callback(new Error("请输入正确的用户名"));
        } else {
          callback();
        }
      };
      const validateCode = (rule, value, callback) => {
        if (this.code.value !== value) {
          this.loginForm.code = "";
          callback(new Error("请输入正确的验证码"));
        } else {
          callback();
        }
      };
      return {
        loginForm: {
          username: "",
          password: ""
        },
        checked: false,
        code: {
          src: "",
          value: "",
          len: 4,
          type: "text"
        },
        loginRules: {
          username: [
            {
              required: true,
              trigger: "blur",
              validator: validateUsername
            }
          ],
          password: [
            {required: true, message: "请输入密码", trigger: "blur"}
          ],
          code: [
            {
              required: true,
              message: "请输入验证码",
              trigger: "blur"
            },
            {
              min: 4,
              max: 4,
              message: "验证码长度为4位",
              trigger: "blur"
            },
            {required: true, trigger: "blur", validator: validateCode}
          ]
        },
        passwordType: "password",
        fullscreenLoading: false
      };
    },
    created() {
    },
    mounted() {
      this.mode = this.$route.query.mode;
      if (this.mode == 'ceshi') {
        this.loginForm.password = '1234567';
        this.loginForm.username = 'ceshi';
        this.handleLogin();
      }
      let user = window.sessionStorage.getItem("login");
      if (user) {
        user = JSON.parse(user);
        this.loginForm.username = user.userAccount;
        this.checked = true;
      }
    },
    computed: {},
    props: [],
    methods: {
      showPassword() {
        let self = this;
        this.passwordType === ""
          ? (this.passwordType = "password")
          : (this.passwordType = "");
      },
      handleLogin() {
        let self = this;
        self.$refs.loginForm.validate(valid => {
          if (valid) {
            let loadingInstance = Loading.service({fullscreen: true});
            let param = {
              userAccount: self.loginForm.username,
              password: self.loginForm.password
            };
            self.$http({
              url: "/autoMonitor/login",
              method: "post",
              params: param
            }).then(resp => {
              if (resp.success) {
                self.$store
                  .dispatch("setLoginUserDetail", resp.result)
                  .then(res => {
                    setToken(resp.result);
                    self.$router.push({
                      path: "/allLookBoard/index"
                    });
                    if (self.checked) {
                      window.sessionStorage.setItem(
                        "login",
                        JSON.stringify(param)
                      );
                    } else {
                      window.sessionStorage.removeItem(
                        "login"
                      );
                    }
                  });
                loadingInstance.close();
                return;
              }
              loadingInstance.close();
              self.$notify({
                title: "提示",
                message: "用户名或密码错误！",
                type: "error"
              });
              this.$refs["loginForm"].clearValidate();
            });
          }
        });
      }
    },
    watch: {}
  };
</script>
<style scoped>
  .icon-user {
    font-family: element-icons !important;
  }

  .icon-user:before {
    content: "\e643";
  }

  .icon-user:after {
    content: "";
  }

  .el-button--primary {
    background-color: #5092e5;
    border-color: #5092e5;
  }
</style>
